const serverUrl = 'http://127.0.0.1:8009/api'
const staticUrl = 'http://localhost:9527'

//const serverUrl = 'https://bkb.gnux.cn/api'
//const staticUrl = 'https://bkb.gnux.cn'

function myRequest(paramsObj, successFun) {
  let sessionId = uni.getStorageSync('sessionid')

  if (sessionId) {
    paramsObj.header = {
      'content-type': 'application/x-www-form-urlencoded',
      cookie: 'bkbsessionid=' + sessionId,
    }
  } else {
    paramsObj.header = {
      'content-type': 'application/x-www-form-urlencoded',
    }
  }
  paramsObj.url = serverUrl + paramsObj.url
  paramsObj.method = 'POST'
  paramsObj.timeout = 5000
  paramsObj.data.channel = 'mini'
  paramsObj.success = successFun
  paramsObj.fail = function () {
    uni.showModal({
      title: '提示',
      content: '网络错误，请求失败',
    })
  }

  uni.request(paramsObj)
}

const showToast = (title) => {
  uni.showToast({
    title: title,
    icon: 'none',
  })
}

const http = (url, data = {}, option = {}) => {
  let hideLoading = option.hideLoading || false
  let hideMsg = option.hideMsg || false
  let token = {}
  let sessionId = uni.getStorageSync('sessionid')
  if (sessionId) {
    token = {
      'content-type': 'application/x-www-form-urlencoded',
      cookie: 'bkbsessionid=' + sessionId,
    }
  } else {
    token = {
      'content-type': 'application/x-www-form-urlencoded',
    }
  }

  if (!hideLoading) {
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: serverUrl + url,
      method: option.method || 'POST',
      header: token,
      data: data,
      success: (res) => {
        if (!hideLoading) uni.hideLoading()
        if (res.data.code == 20000) {
          resolve(res)
          return
        } else {
          uni.showModal({
            title: '提示',
            content: res.data.message,
          })
          return
        }
      },
      fail: (err) => {
        if (!hideLoading) uni.hideLoading()
      },
    })
  })
}

function showToastMsg(msg = '', success = function () {}) {
  uni.showToast({
    icon: 'none',
    title: msg,
    success: success,
  })
}

export { myRequest, showToastMsg, http, serverUrl, staticUrl }
